package com.zzyl.common.ai;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

public class BaiduQianfanService {

    private RestTemplate restTemplate = new RestTemplate();

    // 百度千帆API地址
    private static final String QIANFAN_API_URL = "https://qianfan.baidubce.com/v2/chat/completions";

    // 你的访问令牌（请替换为实际的完整token）
    private static final String ACCESS_TOKEN = "bce-v3/ALTAK-msWHLbFyYyPwo8yxOCS0S/eb3d2f4c14fc36b78fd15f5d120e192de877ef78";

    public String callQianfanChatCompletion(String userMessage) {
        try {
            // 1. 创建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(ACCESS_TOKEN); // 设置Bearer Token

            // 2. 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "ernie-lite-8k");

            // 构建消息列表
            List<Map<String, String>> messages = new ArrayList<>();

            // 系统消息
            Map<String, String> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "平台助手");
            messages.add(systemMessage);

            // 用户消息
            Map<String, String> userMessageMap = new HashMap<>();
            userMessageMap.put("role", "user");
            userMessageMap.put("content", userMessage);
            messages.add(userMessageMap);

            requestBody.put("messages", messages);

            // 3. 创建HttpEntity
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            // 4. 发送POST请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                    QIANFAN_API_URL,
                    requestEntity,
                    String.class
            );

            // 5. 处理响应
            if (response.getStatusCode().is2xxSuccessful()) {
                String json = response.getBody();
                JSONObject jsonObject = JSONUtil.parseObj(json);
                JSONArray choices = jsonObject.getJSONArray("choices");
                JSONObject choice = choices.getJSONObject(0);
                String content = choice.getJSONObject("message").getStr("content");
                return content;
            } else {
                throw new RuntimeException("API调用失败，状态码: " + response.getStatusCode() +
                        ", 响应: " + response.getBody());
            }

        } catch (Exception e) {
            throw new RuntimeException("调用百度千帆API时发生错误: " + e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        String userMessage = "你好";
        BaiduQianfanService baiduQianfanService = new BaiduQianfanService();
        String result = baiduQianfanService.callQianfanChatCompletion(userMessage);
        System.out.println("API响应: " + result);

    }
}

// 请求体对象类
@Data
class ChatCompletionRequest {
    private String model;
    private List<Message> messages = new ArrayList<>();
    private Double temperature; // 可选参数
    private Integer max_tokens; // 可选参数

}

// 消息对象类
@Data
class Message {
    private String role;
    private String content;

}

// 响应对象类（简化版，根据实际API响应结构调整）
@Data
class QianfanResponse {
    private String id;
    private String object;
    private Long created;
    private String model;
    private List<Choice> choices;
    private Usage usage;

}

@Data
class Choice {
    private Integer index;
    private Message message;
    private String finish_reason;

}

@Data
class Usage {
    private Integer prompt_tokens;
    private Integer completion_tokens;
    private Integer total_tokens;

}